#include <QWidgetList>

#include <QDebug>
#include "cvactivitywiget.h"
#include "ui_cvactivitywiget.h"
#include "bizlogic/blogmanager.h"
#include "bizlogic/linkmanager.h"
#include "util/cvutil.h"
#include "cvsession.h"

CVActivityWidget::CVActivityWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CVActivityWiget)
{
    ui->setupUi(this);
}

CVActivityWidget::CVActivityWidget(CVActivity *activity, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CVActivityWiget)
{
    ui->setupUi(this);

    //LinkManager *linkMgr = new LinkManager();
    ui->ActivityTitle->setText(activity->getTranslateMessage());
    connect(ui->ActivityTitle, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));
    if (activity->getObjectType() == "file")
    {
        QString mimeType = activity->getMimeType();
        if (mimeType == "image/jpeg")
        {
            ui->ActivityDesc->setText("[JPEG]");
            CVSession *session = CVSession::get();
            QUrl *url = new QUrl();
            url->setScheme("https");
            url->setHost(session->getCurrentNetwork()->getUrl());
            url->setPath("/dl/file/" + activity->getObjectId() + "/thumbnail/small");
            ui->ActivityDesc->setImageUrl(*url, false);
            connect(ui->ActivityDesc, SIGNAL(clicked(CVImage*)), this, SLOT(imageClicked(CVImage*)));
        }
    }
    else
    {
        QString desc = activity->getDescription();
        if (desc.trimmed().isEmpty())
        {
            ui->ActivityDesc->setVisible(false);
        }
        else
        {
            ui->ActivityDesc->setText(activity->getDescription());
            ui->ActivityDesc->setToolTip(activity->getDescription());
        }
    }
    connect(ui->ActivityDesc, SIGNAL(linkActivated(QString)), this, SLOT(linkActivated(QString)));

    ui->ActivityTime->setText(activity->getPosted());
    ui->userIcon->setImageUrl(activity->getSubjectIcon());
}

CVActivityWidget::~CVActivityWidget()
{
    delete ui;
}

void CVActivityWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void CVActivityWidget::linkActivated(const QString &str)
{
    CVTabWidget *tabWidget = CVUtil::getTabWidget(this);

    LinkManager *linkMgr = new LinkManager();
    linkMgr->handleLink(str, tabWidget);
}

void CVActivityWidget::imageClicked(CVImage *image)
{
    QUrl url = image->getImageUrl();
    QString urlString = url.toString();
    urlString = urlString.replace("small", "large");
    ui->ActivityDesc->setImageUrl(urlString, false);
}
